﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Intex.Db.Service
{
    public class RecoveryService
    {
        private int _printIndex = 0;
        private string _printDate = "";
        private const string DATEFORMAT = "yyyy-MM-dd";
        private const string RECOVERYSQL = "select it.* from Item it inner join ItemValue iv on it.ItemId=iv.ItemId and iv.Value='{0}' inner join ItemType itp on iv.ItemTypeId = itp.ItemTypeId and itp.Alias='{2}' where it.CreatedDate like '{1}%';";

        private bool _isRecoveryMode = false;

        public bool IsRecoveryMode
        {
            get
            {
                return _isRecoveryMode;
            }
            set
            {
                _isRecoveryMode = value;
                if (!_isRecoveryMode)
                {
                    _printIndex = 0;
                }
            }
        }

        public string GetRecoverySql()
        {
            if (!_isRecoveryMode) return "";
            _printIndex++;
            return string.Format(RECOVERYSQL, _printIndex, _printDate, Models.Config.IndexAlias);
        }

        public bool CheckData(int orderIndex, DateTime printDate)
        {
            if (!_isRecoveryMode && _printIndex == 0)
            {
                _printIndex = orderIndex;
                _printDate = printDate.ToString(DATEFORMAT);
                return true;
            }
            int prevOrderIndex = orderIndex--;
            string prevDate = printDate.ToString(DATEFORMAT);
            if (prevOrderIndex != _printIndex)
            {
                if (prevDate == _printDate)
                {
                    _isRecoveryMode = true;
                    return false;
                }
                else
                {
                    _printIndex = orderIndex;
                    _printDate = prevDate;
                    return true;
                }
            }
            _printIndex++;
            _printDate = prevDate;
            return true;
        }
    }
}
